package com.kpf.springcloud.service.impl;

import com.kpf.springcloud.common.ResponseEnum;
import com.kpf.springcloud.exception.BusinessException;
import com.kpf.springcloud.mapper.KpfVisitTopicMapper;
import com.kpf.springcloud.pojo.KpfTopic;
import com.kpf.springcloud.pojo.KpfVisitTopic;
import com.kpf.springcloud.service.IKpfTopicService;
import com.kpf.springcloud.service.IKpfVisitTopicService;
import com.kpf.springcloud.service.ITokenService;
import com.kpf.springcloud.utils.GeneralUtil;
import com.kpf.springcloud.utils.LocalIpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author shiwen
 * @date 2021/4/6
 */
@Service
public class KpfVisitTopicServiceImpl extends BaseServiceImpl<KpfVisitTopicMapper, KpfVisitTopic> implements IKpfVisitTopicService {

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IKpfTopicService topicService;

    /**
     * 统计帖子访问人数
     */
    @Override
    public void countVisitors(int topicId) {
        String token = tokenService.verifyToken();
        // 判断token是否过期
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        KpfTopic kpfTopic = topicService.getById(topicId);
        if (GeneralUtil.isObjNull(kpfTopic)) {
            throw new BusinessException(ResponseEnum.TOPIC_NOT_EXIST);
        }
        // 用户id
        int userId = Integer.parseInt(token.split("-")[0]);
        String localIpAddr = LocalIpUtils.getLocalIpAddr();
        KpfVisitTopic kpfVisitTopic = KpfVisitTopic.builder().ipAddress(localIpAddr).topicId(topicId).userId(userId).build();
        save(kpfVisitTopic);
    }

}